import * as Blockly from 'blockly/core'

// 创建一个空对象
const objectCreateJson = {
  type: 'object_create',
  message0: '空对象',
  output: 'Object',
  colour: 180,
  tooltip: '创建一个空对象',
  helpUrl: ''
}

Blockly.Blocks['object_create'] = {
  init: function () {
    this.jsonInit(objectCreateJson)
  }
}

Blockly.JavaScript['object_create'] = function () {
  const code = `{}`
  // 值块必须返回一个包含两个值的列表 代码和相应的值
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]
}

// 设置对象属性的值
const objectSetJson = {
  type: 'object_value_set',
  message0: '设置对象 %1 的属性 %2 值为 %3',
  args0: [
    {
      'type': 'input_value',
      'name': 'OBJECT',
      'check': 'Object'
    },
    {
      'type': 'input_value',
      'name': 'OBJECT_KEY',
      'check': 'String'
    },
    {
      'type': 'input_value',
      'name': 'OBJECT_VALUE'
    }
  ],
  previousStatement: null,
  nextStatement: null,
  inputsInline: true,
  colour: 180,
  tooltip: '设置对象的属性值',
  helpUrl: ''
}

Blockly.Blocks['object_value_set'] = {
  init: function () {
    this.jsonInit(objectSetJson)
  }
}

Blockly.JavaScript['object_value_set'] = function (block) {
  const obj = Blockly.JavaScript.valueToCode(
    block,
    'OBJECT',
    Blockly.JavaScript.ORDER_FUNCTION_CALL
  ) || '{}'
  const objectKey = Blockly.JavaScript.valueToCode(
    block,
    'OBJECT_KEY',
    Blockly.JavaScript.ORDER_FUNCTION_CALL
  ) || '\'\''
  const objectValue = Blockly.JavaScript.valueToCode(
    block,
    'OBJECT_VALUE',
    Blockly.JavaScript.ORDER_FUNCTION_CALL
  ) || '\'\''

  return `${obj}[${objectKey}] = ${objectValue}\n`
}

// 获取对象属性的值
const objectGetJson = {
  type: 'object_value_get',
  message0: '获取对象 %1 的属性 %2 的值',
  args0: [
    {
      'type': 'input_value',
      'name': 'OBJECT',
      'check': 'Object'
    },
    {
      'type': 'input_value',
      'name': 'OBJECT_KEY',
      'check': 'String'
    }
  ],
  output: null,
  colour: 180,
  tooltip: '获取对象指定属性的值',
  helpUrl: ''
}

Blockly.Blocks['object_value_get'] = {
  init: function () {
    this.jsonInit(objectGetJson)
  }
}

Blockly.JavaScript['object_value_get'] = function (block) {
  const obj = Blockly.JavaScript.valueToCode(
    block,
    'OBJECT',
    Blockly.JavaScript.ORDER_FUNCTION_CALL
  ) || '{}'
  const objectKey = Blockly.JavaScript.valueToCode(
    block,
    'OBJECT_KEY',
    Blockly.JavaScript.ORDER_FUNCTION_CALL
  ) || '\'\''
  const code = `${obj}[${objectKey}]`
  return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]
}
